package com.javaear.json4bean.core;

import com.javaear.json4bean.util.IOUtils;
import com.javaear.json4bean.util.StringUtils;

import java.io.File;
import java.io.IOException;

/**
 * @author aooer
 */
public class JsonRender {

    /**
     * 渲染javaBean
     *
     * @param jsonStr   json字符串
     * @param className 类名
     */
    public void reander(String jsonStr, String className, String packageName, String destDir) throws IOException {
        reander(new JsonObject(jsonStr), className, packageName, destDir);
    }

    /**
     * 渲染javaBean
     *
     * @param jsonObj   jsonObj
     * @param className 类名
     */
    void reander(JsonObject jsonObj, String className, String packageName, String destDir) throws IOException {
        final String javaBeanContent = StringUtils.LINE + JsonSerializer.serialize(jsonObj.getJsonObj(), className, StringUtils.PREFIX_SPACE);
        IOUtils.write((StringUtils.isEmpty(packageName) ? "" : "package " + packageName + ";" + StringUtils.LINE + StringUtils.LINE) + (javaBeanContent.contains("private List<") ? "import java.util.List;" + javaBeanContent : javaBeanContent), destDir + File.separatorChar + className + ".java");
    }

    /* 延迟加载内部类 */
    private static class JsonRenderHolder {
        private static JsonRender INSTANCE = new JsonRender();
    }

    /* 单例，实例获取方法 */
    public static JsonRender getInstance() {
        return JsonRenderHolder.INSTANCE;
    }

    private JsonRender() {
    }
}
